<?php
/**
 * AuditBehavior class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright  Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

/**
 * Audit behavior allows for updating record audit info automatically.
 */
class AuditBehavior extends CActiveRecordBehavior
{
    /**
     * Actions to be taken before saving the record.
     */
    public function beforeSave()
    {
	    $now = new CDbExpression('NOW()');
        $userId = Yii::app()->user->id;
        
        // We are creating a new record.
        if ($this->owner->isNewRecord)
        {
            if ($this->owner->hasAttribute('created'))
               $this->owner->created = $now;
            
            if ($this->owner->hasAttribute('creatorId'))
               $this->owner->creatorId = $userId;
        }
        // We are updating an existing record.
        else
        {
            if ($this->owner->hasAttribute('updated'))
                $this->owner->updated = $now;
            
            if ($this->owner->hasAttribute('updaterId'))
               $this->owner->updaterId = $userId;
        }
    }
}